package com.paddyi.controller;

import com.paddyi.jwt.JwtConfigProperty;
import com.paddyi.jwt.JwtUtil;
import com.paddyi.commons.http.AuthHeader;
import com.paddyi.commons.http.HttpResult;
import com.paddyi.commons.http.SsoHttpResult;
import com.paddyi.commons.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @program: paddyi
 * @description: 登录服务器相关的Controller
 * @author: paddy
 * @create: 2019-05-09 22:34
 **/
@Controller
@RequestMapping()
public class SsoController {
    @Autowired
    private JwtConfigProperty jwtConfig;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Value("${jwt.serverExpirationMinute}")
    String serverExpirationMinute;

    /**
     *
     * @param request
     * @param response
     * @param redirectUrl 回调url
     * @return
     */
    @RequestMapping(value = "/refreshToken")
    public SsoHttpResult checkToken(HttpServletRequest request, HttpServletResponse response, String redirectUrl) {

        String userIdAndRoles = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String serverToken = jwtUtil.generateToken(userIdAndRoles,true);
        String clientToken = jwtUtil.generateToken(userIdAndRoles,false);
        stringRedisTemplate.opsForValue().set(userIdAndRoles, userIdAndRoles, Long.valueOf(serverExpirationMinute) + 1, TimeUnit.MINUTES); // 将资源信息存入redis,时间比jwt过期时间长一分钟，防止bug
        Cookie cookie = new Cookie(this.jwtConfig.getHeader(), jwtConfig.getTokenHead() + serverToken);
        response.addCookie(cookie);
        return SsoHttpResult.resultToken(jwtConfig.getTokenHead() + clientToken, redirectUrl);
    }

    @RequestMapping("/index")
    public Object index() {
        System.out.println("index");
        return "index";
    }

    @RequestMapping("/signin")
    public Object signin() {
        return "signin";
    }

    @RequestMapping("/signup")
    public Object signup() {
        return "signup";
    }

    @RequestMapping("/login")
    public HttpResult login() {
        return HttpResult.error(402, "请登录");
    }
}
